package gameLogic;

public class Login {

	private static Login instance;
	private User loggedUser;
	private UserSqlHelper helper;

	private Login(User loggedUser, UserSqlHelper helper) {

		if (helper == null) {
			throw new IllegalArgumentException(
					"null helper passed to login constr");
		}
		this.loggedUser = loggedUser;
		this.helper = helper;

	}

	public static Login getInstance(User loggedUser, UserSqlHelper helper) {

		if (instance == null) {
			instance = new Login(loggedUser, helper);
		}

		return instance;
	}

	public boolean login(String username, String password) {

		if (loggedUser != null) {
			return false;
		}

		User user = helper.getUser(username, password);

		if (user == null) {
			return false;
		}

		loggedUser = user;
		return true;

	}

	public boolean usernameExistsInDb(String username) {
		return helper.usernameExistsInDb(username);
	}

	public boolean registerUser(String username, String password) {

		if (usernameExistsInDb(username)) {
			return false;
		}
		User user = new User(username);

		helper.addUser(user, password);

		loggedUser = user;

		return true;
	}

	public void updateUserInfo() {
		helper.updateUserInfo(loggedUser);
	}

	public void logOut() {
		loggedUser = null;
	}

	public User getLoggedUser() {
		return loggedUser;
	}
}
